package com.sghd.football.module.game.facade;

import com.sghd.common.socket.core.ResultCallback;
import com.sghd.common.socket.session.Session;
import com.sghd.common.socket.session.SessionManager;
import com.sghd.football.module.data.service.DataService;
import com.sghd.football.module.game.facade.model.ConneReq;
import com.sghd.football.module.game.facade.model.JoinResult;
import com.sghd.football.module.game.service.DialogService;
import com.sghd.football.module.game.service.GameService;
import com.sghd.football.module.game.service.model.Window;
import com.sghd.football.net.ServerHandler;
import com.sghd.football.utils.ManagedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * \* Created with 王创辉.
 * \* Date: 2018/5/18
 * \* Time: 12:07
 * \* @desc: 游戏门面服务实现类
 */
@Component
public class GameFacade implements ServerHandler {
    private static final Logger logger = LoggerFactory.getLogger(GameFacade.class);

    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private GameService gameService;
    @Autowired
    private DialogService dialogService;
    @Autowired
    private DataService dataService;

    @Override
    public void conn(Session session, ConneReq req) {
        long playerId = req.getPlayerId();
        try {
            //boolean success = dataService.checkToken(req.getPlayerId(), req.getToken(), req.getPub(), req.getPlatformId());
            boolean success = true;
            if (success) {//token 验证成功
                Session prev = sessionManager.getSession(playerId);
                if (prev != null) {
                    dialogService.dialog(Window.MANEY_LOGIN, playerId);
                    sessionManager.kick(Session.KICK, playerId);//踢下线
                }
                sessionManager.bind(session, playerId);
                gameService.match(playerId);
            } else {
                dialogService.dialog(Window.TOKEN_FIAL, playerId);
                sessionManager.kick(Session.NORMAL, playerId);//踢除玩家下线
            }
        } catch (ManagedException e) {
            dialogService.dialog(e.getWindow(), playerId);
        } catch (Exception e) {
            logger.error("初始化连接发生未知错误！", e);
            dialogService.dialog(Window.UNKOUNW_ERROR, playerId);
        }
    }

    @Override
    public void enter(Long playerId, int configId, int gameId, ResultCallback<JoinResult> callback) {
        try {
            gameService.enter(playerId, configId, gameId, callback);
        } catch (ManagedException e) {
            dialogService.dialog(e.getWindow(), playerId);
        } catch (Exception e) {
            logger.error("进入房间发生未知错误！", e);
            dialogService.dialog(Window.UNKOUNW_ERROR, playerId);
        }
    }

    @Override
    public Map<String, Object> operator(long playerId, int betIdx) {
        try {
            return gameService.operator(playerId, betIdx);
        } catch (ManagedException e) {
            dialogService.dialog(e.getWindow(), playerId);
        } catch (Exception e) {
            logger.error("旋转发生未知错误[{}]", new Object[]{e.getMessage()});
            dialogService.dialog(Window.UNKOUNW_ERROR, playerId);
        }
        return null;
    }


    /********************************************************************************************************/


    /**
     * 断线、超时、被踢下线时触发
     * @param session
     * @param cause
     */
    @Override
    public void sessionClosed(Session session, int cause) {
        try {
            if (session == null) {
                return;
            }
            switch (cause) {
                case Session.KICK://被踢(挤)下线
                case Session.INTERRUPT:// 断线
                    Object identity = session.getIdentity();
                    if (identity != null) {
                        gameService.submit(() -> {
                            gameService.exit((long) identity, false);
                        });
                    }
                    break;
                case Session.NORMAL:
                    break;
            }
            if (logger.isDebugEnabled()) {
                logger.debug("SESSION[{}]->CLOSED[{}]->IDENTITY[{}]", session.getId(), cause, session.getIdentity());
            }
        } catch (Exception e) {
            logger.error("session close error:{}", e);
        }
    }

    /** 会话被创建*/
    @Override
    public void sessionOpened(Session session) {
        if (logger.isDebugEnabled()) {
            logger.debug("SESSION[{}]->OPENED", session.getId());
        }
    }
}
